# @Time : 2024-10-23 11:34
# @Author : Fioman 
# @Phone : 13149920693

lst = [1, 2, 3, 3, 3, 4, 5, 6]
for i in lst:
    if i == 3:
        lst.remove(3)
print(lst)  # [1, 2, 3, 4, 5, 6]

# 遍历的本质就是索引一直往下走
# 第三次迭代: i = 3, lst.remove(3) 此时的lst = [1,2,3,3,4,5,6]
# 第四次迭代: i = 3, lst.remove(3) 此时的索引 i = 3,然后索引为2的位置上也是3,那个3就删除不了了
# 第五次迭代: i= 5, 因为4前移了.

lst = [1, 2, 3, 3, 3, 4, 5, 6]
for i in lst:
    if i == 3:
        lst.remove(3)
    if i == 4:
        lst.remove(4)
print(lst)  # [1, 2, 3, 4, 5, 6]

lst = [1, 2, 3, 3, 3, 4, 5, 6]
# 如何避免这种情况呢,使用拷贝副本或者使用列表推导式,或者使用while循环
for i in lst[:]:  # 创建副本
    if i == 3 or i == 4:
        lst.remove(i)
print(lst)

lst = [1, 2, 3, 3, 3, 4, 5, 6]
for i in lst.copy():
    if i == 3 or i == 4:
        lst.remove(i)
print(lst)

lst = [1, 2, 3, 3, 3, 4, 5, 6]
while 3 in lst or 4 in lst:
    if 3 in lst:
        lst.remove(3)
    if 4 in lst:
        lst.remove(4)
print(lst)
lst = [1, 2, 3, 3, 3, 4, 5, 6]
# 列表推导式
lst = [x for x in lst if x != 3 and x != 4]
print(lst)
